<template>
    <div>
        <el-form label-width="100px">
            <el-form-item label="SPU名称">{{ spuInfo.spuName }}</el-form-item>
            <el-form-item label="SKU名称">
                <el-input placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
            </el-form-item>
            <el-form-item label="价格">
                <el-input type="number" placeholder="请输入价格" v-model="skuForm.price"></el-input>
            </el-form-item>
            <el-form-item label="重量">
                <el-input type="number" placeholder="请输入重量" v-model="skuForm.weight"></el-input>
            </el-form-item>
            <el-form-item label="规格描述">
                <el-input type="textarea" rows="4" placeholder="规格描述" v-model="skuForm.skuDesc"></el-input>
            </el-form-item>
            <el-form-item label="平台属性">
                <el-form label-width="80px" :inline="true">
                    <el-form-item :label="attr.attrName" v-for="attr in attrList" :key="attr.id">
                        <el-select v-model="attr.attrIdValueId">
                            <el-option :value="`${attr.id}:${item.id}`" v-for="item in attr.attrValueList" :key="item.id" :label="item.valueName"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-form label-width="80px" :inline="true">
                    <el-form-item :label="saleAttr.saleAttrName" v-for="saleAttr in saleAttrList" :key="saleAttr.id">
                        <el-select v-model="saleAttr.saleAttrIdValueId">
                            <el-option :value="`${saleAttr.id}:${item.id}`" v-for="item in saleAttr.spuSaleAttrValueList" :key="item.id" :label="item.saleAttrValueName"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="图片列表">
                <el-table border stripe :data="imgList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50" />
                    <el-table-column label="图片">
                        <template #default="{ row }">
                            <img :src="row.imgUrl" style="width: 100px" alt="" />
                        </template>
                    </el-table-column>
                    <el-table-column label="名称" prop="imgName"></el-table-column>
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <el-button type="primary" size="default" @click="selectDefaultImg(row, imgList)" v-if="row.isDefault === '0'">设为默认</el-button>
                            <el-tag type="primary" v-else size="default">默认图片</el-tag>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="save">保存</el-button>
                <el-button type="default" @click="emit('changeShowState', 1)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "SkuForm",
});
</script>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { SpuImageItemType, SpuInfoType } from "@/types/spu";
import { ElMessage } from "element-plus";
import { reqAttrList } from "@/api/attr";
import { useCategoryStore } from "@/stores/category";
import { storeToRefs } from "pinia";
import { reqSpuImageList, reqSpuSaleAttrList } from "@/api/spu";
import type { AttrType } from "@/types/attr";
import type { SpuSaleAttrListType, SpuImageListType } from "@/types/spu";
import type { skuAttrValueListType, skuImageListType, skuInfoItemDetailType, skuSaleAttrValueListType } from "@/types/sku";
import { reqAddSku } from "@/api/sku";

const props = defineProps<{ spuInfo: SpuInfoType }>(); // 接收父组件传递的spuInfo
const emit = defineEmits(["changeShowState"]); // 接收父组件传递的changeShowState事件
const categoryStore = useCategoryStore();
const { categoryId1, categoryId2, categoryId3 } = storeToRefs(categoryStore);
/*
 * @description: 初始化数据
 * */
// 定义平台属性/销售属性/图片列表数据
const attrList = ref<AttrType>([]);
const saleAttrList = ref<SpuSaleAttrListType>([]);
const imgList = ref<SpuImageListType>([]);

// 封装初始化获取平台属性/销售属性/图片列表数据的方法
const initData = async () => {
    const p1 = reqAttrList(categoryId1.value as number, categoryId2.value as number, categoryId3.value as number); // 获取平台属性列表
    const p2 = reqSpuSaleAttrList(props.spuInfo.id as number); // 获取销售属性列表
    const p3 = reqSpuImageList(props.spuInfo.id as number); // 获取图片列表
    try {
        const [attrListRes, saleAttrListRes, imgListRes] = await Promise.all([p1, p2, p3]);
        attrList.value = attrListRes;
        saleAttrList.value = saleAttrListRes;
        imgList.value = imgListRes;
        imgList.value.forEach(item => {
            item.isDefault = "0";
        });
    } catch (e: any) {
        ElMessage.error(e.message);
    }
};
// 初始化数据
onMounted(() => {
    initData();
});

/*
 * @description: 收集数据
 * */
// 初始化收集数据
const skuForm = ref<skuInfoItemDetailType>({
    spuId: props.spuInfo.id as number, //所在的spuId
    price: 0, //当前sku的价格
    skuName: "", //当前sku的名称
    skuDesc: "", //当前sku的描述
    weight: "", //当前sku的重量
    tmId: props.spuInfo.tmId, //当前sku所在的品牌id
    category3Id: categoryId3.value as number, //当前sku所在的三级分类的id
    skuDefaultImg: "", //当前sku的默认的图片
    isSale: 1, //是否上架,1:上架,0:下架
    skuImageList: [], //当前sku图片列表
    skuAttrValueList: [], //当前sku属性值列表
    skuSaleAttrValueList: [], //当前sku销售属性值列表
});

// 收集图片列表数据
interface skuImgListType {
    id: number;
    imgName: string;
    imgUrl: string;
    spuId: number;
    isDefault: string;
}

const skuImageList = ref<skuImgListType>([]);
const handleSelectionChange = (val: skuImgListType) => {
    skuImageList.value = val; // 注意修改类型
};
// 设置默认图片的回调
const selectDefaultImg = (row: SpuImageItemType, imgList: SpuImageListType) => {
    imgList.forEach(item => {
        item.isDefault = "0";
    });
    row.isDefault = "1";
    skuForm.value.skuDefaultImg = row.imgUrl; // 设置默认图片
};

/*
 * @description: 提交数据
 * */
const save = async () => {
    // 整理数据
    // 1.整理图片列表数据
    skuForm.value.skuImageList = skuImageList.value.map(item => {
        return {
            imgName: item.imgName,
            imgUrl: item.imgUrl,
            spuImgId: item.id,
            isDefault: item.isDefault,
        };
    });
    // 2.整理平台属性列表数据
    skuForm.value.skuAttrValueList = attrList.value.reduce((prev, item) => {
        if (item.attrIdValueId) {
            const [attrId, attrValueId] = item.attrIdValueId.split(":");
            prev.push({
                attrId: +attrId,
                valueId: +attrValueId,
            });
        }
        return prev;
    }, [] as skuAttrValueListType);
    // 3.整理销售属性值列表数据
    skuForm.value.skuSaleAttrValueList = saleAttrList.value.reduce((prev, item) => {
        if (item.saleAttrIdValueId) {
            const [saleAttrId, saleAttrValueId] = item.saleAttrIdValueId.split(":");
            prev.push({
                saleAttrId: +saleAttrId,
                saleAttrValueId: +saleAttrValueId,
            });
        }
        return prev;
    }, [] as skuSaleAttrValueListType);
    // 4.提交数据
    try {
        await reqAddSku(skuForm.value);
        ElMessage.success("添加成功");
        emit("changeShowState", 1);
    } catch (e: any) {
        ElMessage.error(e.message);
    }
};
</script>

<style scoped></style>
